angular.module('planInput', ['toastr'])
    .controller('planInputController',
        ['$scope', '$http', 'toastr', '$compile',
            function ($scope, $http, toastr, $compile) {
                var memberMap = {};
                var roleMap = {};
                var projects = {};
                var projectMap = {};
                var myProjectMap = {};
                var newDetailCount = 0;
                var plan_id = 0;
                var uid = parseInt($("#userId").html());
                $scope.extra = {
                    'risk': {},
                    'change': {},
                    'training': {}
                };
                $scope.detail = {};
                $scope.selectAll = {};
                $scope.selectAllExtra = {};
                $scope.currentEdit = "";

                if (!!$.cookie("toast")) {
                    toastr.success($.cookie("toast"));
                    $.cookie("toast", "");
                }


                $http.get('/user/mapping').success(function (data) {
                    for (var i in data.role) {
                        if (data.role[i] !== 'admin') {
                            memberMap[i] = data.name[i];
                            roleMap[i] = data.role[i];
                        }
                    }
                });

                $scope.getDetailAndExtraInfo = function () {
                    $http.post('/project/findAll', {}).success(function (res) {
                        res.forEach(function (e) {
                            projects[e.p_name] = e.p_id;
                            projectMap[e.p_id] = e.p_name;
                            if (e.project_pm == uid) {
                                myProjectMap[e.p_id] = e.p_name;
                            }
                        });
                        $http.post('/plan/find', {status: "latest"}).success(function (plan) {
                            if (plan.length === 0) {
                                $("#announcement").html("暂无计划安排,请等待通知，3秒后跳转至查看页面");
                                $(".announcement").modal();
                                setTimeout(function () {
                                    window.location.href = "/plan/find";
                                }, 3000);
                            }

                            plan_id = plan[0].pl_id;
                            $.cookie("latest", plan_id);

                            if (!!plan[0].next_plan && plan[0].next_plan != "暂无") {
                                $("#announcement").html(plan[0].next_plan);
                                $(".announcement").modal();
                            }
                        });
                        $http.post('/plan/detail/find', {status: "latest", pm_id: uid}).success(function (detail) {
                            detail.forEach(function (e) {
                                if (!$scope.detail[e.fk_usr]) {
                                    $scope.detail[e.fk_usr] = {};
                                }
                                e.p_name = projectMap[e.fk_prj];
                                e.contribute = e.percentage * 100;
                                $scope.detail[e.fk_usr][e.fk_prj] = e;
                            });
                            $scope.editDetail(uid);
                        });
                        $http.post('/plan/extra/find', {status: "latest", pm_id: uid}).success(function (extra) {
                            extra.forEach(function (e) {
                                $scope.extra[e.type][e.pe_id] = e;
                            });
                            $scope.editExtra("risk");
                            $scope.editExtra("training");
                            $scope.editExtra("change");
                        })
                    });
                };
                $scope.getDetailAndExtraInfo();

                $scope.editDetail = function (id) {
                    $scope.currentEdit = memberMap[id];
                    $(".plan-detail").each(function () {
                        $(this).remove();
                    });
                    $(".member").each(function () {
                        $(this).removeClass("active");
                    });
                    $("#member" + id).addClass("active");
                    if (!$scope.detail[id]) {
                        $scope.detail[id] = {};
                        for (var i in myProjectMap) {
                            $scope.detail[id][i] = {
                                p_name: myProjectMap[i]
                            }
                        }
                        for (var i in projectMap) {
                            if (!(i in myProjectMap)) {
                                $scope.detail[id][i] = {
                                    p_name: projectMap[i]
                                }
                            }
                        }
                    }
                    $scope.selectAll[id] = false;
                    var html = '<li class="list-group-item list-group-item-success plan-detail">\
                    <div class="col-md-2 project" style="padding: 0"><span>&nbsp;选择</span>\
                <input style="position: relative;top:2px;" type="checkbox" ng-model="selectAll[' + id + ']" ng-change="toggleSelectDetail(' + id + ')" /></div>\
                <div class="col-md-7 project"><span>项目名称</span></div>\
                <div class="col-md-2 percentage" style="padding: 0">&nbsp;&nbsp;&nbsp;投入百分比</div>\
                </li>';
                    for (var e in $scope.detail[id]) {
                        if (!!$scope.detail[id][e] && e in myProjectMap) {
                            if (!!$scope.detail[id][e].p_name) {
                                html += '<li class="list-group-item plan-detail" id="plan-detail-' + id + '-' + e + '" >\
                        <div class="col-md-2 project"><input name="select" type="checkbox" ng-model="detail[' + id + '][' + e + '].selected" \
                         style="position: relative;top:5px;" class="part-one" /></div>\
                        <div class="col-md-7 project">\
                        <span style="position: relative;top:5px;" ng-bind="detail[' + id + '][' + e + '].p_name"></span>\
                        </div>\
                        <div class="col-md-3 percentage">\
                        <div class="col-md-8 kick-padding-margin"><input type="number" ng-change="validatePercent(detail[' + id + '][' + e + '])" class="form-control  input-sm"\
                        style="padding: 1px 2px 1px 12px" ng-model="detail[' + id + '][' + e + '].contribute"></div>\
                        <div class="col-md-4" style="padding: 5px 0">%</div>\
                        </div>\
                        </li>';
                            } else {
                                $scope.detail[id][e] = false;
                            }
                        }
                    }

                    for (var e in $scope.detail[id]) {
                        if (!!$scope.detail[id][e] && !(e in myProjectMap)) {
                            if (!!$scope.detail[id][e].p_name) {
                                html += '<li class="list-group-item plan-detail" id="plan-detail-' + id + '-' + e + '" >\
                        <div class="col-md-2 project"><input name="select" type="checkbox" ng-model="detail[' + id + '][' + e + '].selected" \
                         style="position: relative;top:5px;" class="part-one" /></div>\
                        <div class="col-md-7 project">\
                        <span style="position: relative;top:5px;" ng-bind="detail[' + id + '][' + e + '].p_name"></span>\
                        </div>\
                        <div class="col-md-3 percentage">\
                        <div class="col-md-8 kick-padding-margin"><input type="number" ng-change="validatePercent(detail[' + id + '][' + e + '])" class="form-control  input-sm"\
                        style="padding: 1px 2px 1px 12px" ng-model="detail[' + id + '][' + e + '].contribute"></div>\
                        <div class="col-md-4" style="padding: 5px 0">%</div>\
                        </div>\
                        </li>';
                            } else {
                                $scope.detail[id][e] = false;
                            }
                        }
                    }

                    var template = angular.element(html);
                    var compiled = $compile(template)($scope);
                    angular.element(".plan-detail-group").append(compiled);
                };

                $scope.editExtra = function (type) {
                    var temp = 0;
                    for (var i in $scope.extra[type]) {
                        if (!!$scope.extra[type][i] && $scope.extra[type][i].content) {
                            ++temp;
                        }
                    }
                    if (temp === 0) {
                        ++newDetailCount;
                        $scope.extra[type][10000 + newDetailCount] = {
                            selected: false,
                            content: "",
                            type: type
                        }
                    }
                    var html = '<li class="list-group-item list-group-item-success plan-extra">\
                    <div class="col-md-1" style="padding: 0"><span>&nbsp;选择</span>\
                <input style="position: relative;top:2px;" type="checkbox" ng-model="selectAllExtra[\'' + type + '\']" ng-change="toggleSelectExtra(\'' + type + '\')" /></div>\
                <div class="col-md-2 project"><span>编号</span></div>\
                <div class="col-md-9 percentage">内容</div>\
                </li>';
                    var count = 0;
                    for (var i in $scope.extra[type]) {
                        html += '<li class="list-group-item plan-extra" id="plan-extra-' + type + '-' + i + '" >\
                        <div class="col-md-1"><input name="select" type="checkbox" ng-model="extra[\'' + type + '\'][' + i + '].selected" \
                         style="position: relative;top:5px;" class="part-' + type + '" /></div>\
                        <div class="col-md-2">\
                        <span style="position: relative;top:5px;" class="extra-number-' + type + '">' + (++count) + '&nbsp;.</span>\
                        </div>\
                        <div class="col-md-9 content"><input type="text" ng-model="extra[\'' + type + '\'][' + i + '].content" class="form-control input-sm" placeholder="输入信息, 长度小于200字符,大于200字符部分不予显示">\
                        </div>\
                        </li>';
                    }
                    var template = angular.element(html);
                    var compiled = $compile(template)($scope);
                    angular.element("#extra-" + type).append(compiled);
                    $("#extra-" + type).attr("next", ++count);
                };

                $scope.addOneExtra = function (type) {
                    var fakeId = 10000 + (++newDetailCount);
                    var count = parseInt($("#extra-" + type).attr("next"));
                    $scope.extra[type][fakeId] = {
                        content: "",
                        selected: false,
                        type: type
                    };
                    var html = '<li class="list-group-item plan-extra" id="plan-extra-' + type + '-' + fakeId + '" >\
                        <div class="col-md-1"><input name="select" type="checkbox" ng-model="extra[\'' + type + '\'][' + fakeId + '].selected" \
                         style="position: relative;top:5px;" class="part-' + type + '" /></div>\
                        <div class="col-md-2">\
                        <span style="position: relative;top:5px;" class="extra-number-' + type + '">' + (count++) + '&nbsp;.</span>\
                        </div>\
                        <div class="col-md-9 content"><input type="text" ng-model="extra[\'' + type + '\'][' + fakeId + '].content" class="form-control input-sm" placeholder="输入信息, 长度小于200字符">\
                        </div>\
                        </li>';
                    var template = angular.element(html);
                    var compiled = $compile(template)($scope);
                    angular.element("#extra-" + type).append(compiled);
                    $("#extra-" + type).attr("next", count);
                };

                $scope.deleteExtra = function (type) {
                    var count = 0;
                    for (var i in $scope.extra[type]) {
                        if ($scope.extra[type][i].selected) {
                            count++;
                            $("#plan-extra-" + type + "-" + i).remove();
                            $scope.extra[type][i] = false;
                        }
                    }
                    if (count === 0) {
                        toastr.warning("未选择任何一项");
                    } else {
                        var total = parseInt($("#extra-" + type).attr("next"));
                        $("#extra-" + type).attr("next", total - count);
                        $(".extra-number-" + type).each(function (index, elememt) {
                            $(elememt).html((index + 1) + "&nbsp;.");
                        })
                    }
                };

                $scope.deleteOneDetail = function () {
                    var mem = $(".active.member").attr("id").substring(6);
                    var details = $scope.detail[mem];
                    var count = 0;
                    for (var i in details) {
                        if (details[i].selected) {
                            count++;
                            $("#plan-detail-" + mem + "-" + i).remove();
                            details[i] = false;
                        }
                    }
                    if (count === 0) {
                        toastr.warning("未选择任何一项");
                    }
                };

                $scope.addOneDetail = function () {
                    var mem = $(".active.member").attr("id").substring(6);
                    var pid = 10000 + (++newDetailCount);

                    $scope.detail[mem][pid] = {
                        p_name: "",
                        extra: "",
                        contribute: ""
                    };

                    var result = [];
                    (function () {
                        for (var i in projectMap) {
                            if (!$scope.detail[mem][i]) {
                                var exist = false;
                                for (var j in $scope.detail[mem]) {
                                    if ($scope.detail[mem][j].p_name == projectMap[i]) {
                                        exist = true;
                                    }
                                }
                                !exist && result.push(projectMap[i]);
                            }
                        }
                    })();
                    if (result.length == 0) {
                        toastr.warning("所有项目已经添加");
                        return;
                    }

                    var html = '<li class="list-group-item plan-detail" id="plan-detail-' + mem + '-' + pid + '" >\
                <div class="col-md-2 project"><input name="select" type="checkbox" ng-model="detail[' + mem + '][' + pid + '].selected" \
                 style="position: relative;top:5px;" class="part-one" /></div>\
                <div class="col-md-7 project">\
                <input id="complete-' + mem + '-' + pid + '" ng-model="detail[' + mem + '][' + pid + '].p_name" class="form-control input-sm complete" />\
                </div>\
                <div class="col-md-3 percentage">\
                <div class="col-md-8 kick-padding-margin"><input type="number" class="form-control input-sm" ng-change="validatePercent(detail[' + mem + '][' + pid + '])" \
                style="padding: 1px 2px 1px 12px" ng-model="detail[' + mem + '][' + pid + '].contribute"></div>\
                <div class="col-md-4" style="padding: 5px 0">%</div>\
                </div>\
                </li>';

                    var template = angular.element(html);
                    var compiled = $compile(template)($scope);
                    angular.element(".plan-detail-group").append(compiled);

                    $("#complete-" + mem + '-' + pid).autocomplete({
                        source: result,
                        select: function (event, ui) {
                            $scope.detail[mem][pid].p_name = ui.item.value;
                            $scope.detail[mem][pid].p_id = parseInt(projects[ui.item.value]);
                        }
                    });

                    $(".complete").each(function () {
                        $(this).on('blur', function () {
                            if (!projects[$(this).val()]) {
                                toastr.warning("没有这个项目或已在列表中，请确认输入");
                            }
                        });
                    });

                };

                $scope.toggleSelectDetail = function (id) {
                    if ($scope.selectAll[id]) {
                        $(".part-one").each(function () {
                            if (!$(this).is(':checked')) {
                                $(this).click();
                            }
                        });
                    } else {
                        $(".part-one").each(function () {
                            if ($(this).is(':checked')) {
                                $(this).click();
                            }
                        });
                    }
                };

                $scope.toggleSelectExtra = function (type) {
                    if ($scope.selectAllExtra[type]) {
                        $(".part-" + type).each(function () {
                            if (!$(this).is(':checked')) {
                                $(this).click();
                            }
                        });
                    } else {
                        $(".part-" + type).each(function () {
                            if ($(this).is(':checked')) {
                                $(this).click();
                            }
                        });
                    }
                };

                $scope.saveAll = function (event) {
                    var htmlCopy = $(event.target).html();
                    $(event.target).removeClass("fa fa-book");
                    $(event.target).html("<span style='padding: 0;margin: 0' class=' fa fa-spinner fa-spin'></span>");

                    var postArray = [];
                    var extraArray = [];
                    var noticePercent = "";
                    for (var i in $scope.detail) {
                        var count = 0;
                        for (var j in $scope.detail[i]) {
                            if (!!$scope.detail[i][j] && !!$scope.detail[i][j].contribute && !!$scope.detail[i][j].p_name) {
                                count += $scope.detail[i][j].contribute;
                                $scope.detail[i][j].percentage = $scope.detail[i][j].contribute / 100.0;
                                !$scope.detail[i][j].p_id &&
                                ($scope.detail[i][j].p_id = parseInt(projects[$scope.detail[i][j].p_name.trim()]));
                                $scope.detail[i][j].pl_id = plan_id;
                                if (!projects[$scope.detail[i][j].p_name.trim()]) {
                                    $(event.target).html(htmlCopy);
                                    $(event.target).addClass("fa fa-book");
                                    toastr.warning("输入项目名称有误：" + $scope.detail[i][j].p_name);
                                    return;
                                }
                                $scope.detail[i][j].pm_id = uid;
                                $scope.detail[i][j].u_id = parseInt(i);
                                postArray.push($scope.detail[i][j]);
                            }
                        }
                        if (count > 100) {
                            $(event.target).html(htmlCopy);
                            $(event.target).addClass("fa fa-book");
                            toastr.warning("对" + memberMap[i] + "分配的总百分比超过100%");
                            return;
                        } else if (count != 100) {
                            noticePercent += memberMap[i]+" ";
                        }
                    }
                    if (noticePercent && !confirm("对" + noticePercent + "分配的总百分比低于100%,确认保存?")) {
                        $(event.target).html(htmlCopy);
                        $(event.target).addClass("fa fa-book");
                        return;
                    }
                    for (var i in $scope.extra) {
                        for (var j in $scope.extra[i]) {
                            if (!!$scope.extra[i][j] && !!$scope.extra[i][j].content &&
                                ($scope.extra[i][j].content.trim()).length != 0 && $scope.extra[i][j].type) {
                                $scope.extra[i][j].plan_id = plan_id;
                                $scope.extra[i][j].pm_id = uid;
                                extraArray.push($scope.extra[i][j]);
                            }
                        }
                    }
                    if (postArray.length == 0 && extraArray.length == 0) {
                        toastr.warning("未填写任何有效数据");
                        $(event.target).html(htmlCopy);
                        $(event.target).addClass("fa fa-book");
                        return;
                    }

                    var parallel = 2;
                    var success = 0;
                    var result = "";
                    $http.post('/plan/detail/add', postArray).success(function (data) {
                        if (data === 'success') {
                            success++;
                            parallel--;
                        } else {
                            result += (data.description + ". ");
                        }
                        displayResult();
                    }).error(function () {
                        --parallel;
                        displayResult();
                    });
                    $http.post('/plan/extra/add', extraArray).success(function (data) {
                        if (data === 'success') {
                            success++;
                            parallel--;
                        } else {
                            result += data.description;
                        }
                        displayResult();
                    }).error(function () {
                        --parallel;
                        displayResult();
                    });
                    function displayResult() {
                        if (!parallel) {
                            if (success == 2) {
                                setTimeout(function () {
                                    window.location.href = window.location.href;
                                }, 300);
                                $.cookie("toast", "保存成功");
                            } else {
                                $(event.target).html(htmlCopy);
                                $(event.target).addClass("fa fa-book");
                                toastr.error("保存失败！" + (!!result ? result : "连接超时"));
                            }
                        }
                    }

                    setTimeout(function () {
                        if (parallel != 0) {
                            $(event.target).html(htmlCopy);
                            $(event.target).addClass("fa fa-book");
                            toastr.error("保存失败！" + (!!result ? result : "连接超时"));
                        }
                    }, 5000);
                };

                $scope.backWard = function () {
                    $(".remove-mem").modal();
                    $("#ensure-remove").on("click", function (event) {
                        window.history.back();
                    });
                };

                $scope.validatePercent = function (data) {
                    if (!!data.contribute && (data.contribute > 100 || data.contribute < 0)) {
                        data.contribute = 0;
                        toastr.warning("百分比输入范围有误");
                    }
                }
            }
        ]);